import { Component, EventEmitter, Input, Output } from '@angular/core';
import { IonicPage, ViewController, NavController, NavParams, AlertController, MenuController,ToastController } from 'ionic-angular';
import { BaseUI } from '../../common/baseUI';


// import * as Cropper from 'cropperjs';

declare var Cropper: any; 


@IonicPage()
@Component({
  selector: 'cropper',
  templateUrl: 'cropper.html'
})
export class CropperComponent extends BaseUI {

  @Input() cropperImgs: any = this.navParams.get('cropperData') || [];
  @Input() useRatio: boolean = this.navParams.get('useRatio') || false;
  @Output() cropped = new EventEmitter();
  
  cropper: any;
  cropperTime: any;
  cropperUseBlob: boolean = false;

  cropperIndex: number = -1;
  cropperResult: any = [];
 
  aspectRatios: any = [
    { name: '自由',    ratio: 'NaN' },
    { name: '1:1',     ratio: 1 },
    { name: '4:3',     ratio: 4/3 },
    { name: '2:3',     ratio: 2/3 },
    { name: '16:9',    ratio: 16/9 },
  ]

  cropperParams = {
    viewMode: 1,
    dragMode: 'move',
    aspectRatio: 1 / 1,
    autoCropArea: 0.8,
    restore: false,
    guides: true,
    center: false,
    highlight: false,
    cropBoxMovable: false,
    cropBoxResizable: true,
    toggleDragModeOnDblclick: true,
    background: false
  }

  outputImgOption = {
    minWidth: 1000,
    minHeight: 1000,
    maxWidth: 1024,
    maxHeight: 1024,
    fillColor: '#fff',
    // imageSmoothingEnabled: false,
    imageSmoothingQuality: 'high'
  }

  croppImg;
  selectAspectRatio = 1;

  constructor(
    public viewCtrl: ViewController,
    public navCtrl: NavController,
    public navParams: NavParams,
    public menuCtrl: MenuController,
    public alertCtrl: AlertController,
    public toastCtrl: ToastController
  ) {
    super();
    // run
    this.cropperIndex = this.cropperImgs.length;
    this.cropperInit();
  }


  ionViewWillEnter() {
    this.menuCtrl.enable(false);
  }

  ionViewWillLeave() {
    this.menuCtrl.enable(true);
  }

  cropperInit() {
    // if nothing to do
    if (this.cropperImgs.length === 0) {
      return this.error();
    }

    this.cropperBuild('', this.cropperImgs[this.cropperIndex - 1])
  }

  cropperBuild(element, imgSrc) {
    clearTimeout(this.cropperTime)
    this.cropperTime = setTimeout(() => {
      const el = element || '.cropp-img'
      const img = document.querySelector(el)
      const parent = img.parentElement

      this.croppImg = document.createElement('img')
      this.croppImg.classList.add('cropp-img')
      this.croppImg.src = imgSrc

      parent.innerHTML = ''
      parent.appendChild(this.croppImg)

      if (typeof this.cropper === 'object') {
        this.cropper.destroy(); // destroy the cropper before
      }
      setTimeout(() => {
        this.cropper = new Cropper(this.croppImg, this.cropperParams)
      }, 0)
    }, 200)
  } 
  getCroppedCanvas(cb) {
    // Upload cropped image to server if the browser supports `HTMLCanvasElement.toBlob`
    if (this.cropper) {
      let cropImg = this.cropper.getCroppedCanvas(this.outputImgOption);

      const base64 = cropImg.toDataURL('image/jpeg', 0.9)
      if (cb) cb(base64, this)
    } else {
      super.showToast(this.toastCtrl ,'无法裁剪，请退出重试')
    }
  }
  cancelCropper() {
    this.cropperIndex --
    if (this.cropperIndex <= 0) { 
      
      // reset cropper data
      this.cropper = undefined
      this.cropperImgs = []
      this.cropperIndex = -1

      this.cropped.emit(this.cropperResult);
      this.viewCtrl.dismiss(this.cropperResult);

    } else {
      this.cropperInit();
    }

  }
  cropcb(base64, target) {
    const tg = target || this

    if (base64) {
      tg.cropperResult.push(base64)
    }
    // if (tg.cropperUseBlob) URL.revokeObjectURL(base64)
    tg.cancelCropper()
  }

  changeAspecRatio(index: number = 1) {
    this.selectAspectRatio = index;
    this.cropperParams.aspectRatio = this.aspectRatios[index].ratio;
    this.cropper.destroy();
    this.cropper = new Cropper(this.croppImg, this.cropperParams)
  }

  error() {
    this.alertCtrl.create({
      title: '没有需要裁剪的图片',
      buttons: [
        {
          text: '我知道了',
          handler: () => {
            this.cropped.emit(this.cropperResult);
            this.viewCtrl.dismiss();
          }
        }
      ]
    }).present();
  }

  // cropperjs end

}
